package com.vrland.web.init;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.google.common.base.Preconditions;
import com.vrland.web.front.RootConfig;
import com.vrland.web.front.dto.Role;
import com.vrland.web.front.dto.User;
import com.vrland.web.front.service.spec.UserService;

public class UserCreator {

	public static void createUser(ApplicationContext context, String loginName,
			String password, Role role) {
		UserService userService = context.getBean(UserService.class);
		User user = User.valueOf(0, loginName, loginName, password, role, true);
		userService.createNewUser(user);
	}

	public static void main(String args[]) {
		ApplicationContext context = initContext();
		CommandLine cmd = parseCommandLineOpts(args);
		String loginName = cmd.getOptionValue("u");
		String password = cmd.getOptionValue("p");
		boolean isAdmin = cmd.hasOption("a");
		Preconditions.checkNotNull(loginName);
		Preconditions.checkNotNull(password);
		createUser(context, loginName, password, isAdmin ? Role.ADMIN
				: Role.USER);
	}

	private static ApplicationContext initContext() {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		context.getEnvironment().addActiveProfile("dev");
		context.register(RootConfig.class);
		context.refresh();
		return context;
	}

	private static CommandLine parseCommandLineOpts(String args[]) {
		Options options = new Options();
		Option usernameOption = new Option("u", true, "login name for user");
		usernameOption.setRequired(true);
		Option passwordOption = new Option("p", true, "password for the user");
		passwordOption.setRequired(true);
		Option adminOption = new Option("a", false, "if this is an admin user");
		options.addOption(usernameOption).addOption(passwordOption)
				.addOption(adminOption);
		CommandLineParser parser = new PosixParser();
		CommandLine cmd = null;
		try {
			cmd = parser.parse(options, args);
		} catch (ParseException e) {
			HelpFormatter formatter = new HelpFormatter();
			formatter.printHelp("UserCreator", options);
			System.exit(-1);
		}
		return cmd;
	}
}
